import Vue from 'vue'
import Vuex from 'vuex'
// 导入axios组件
import axios from 'axios'
// 将Vuex注册为全局组件
Vue.use(Vuex)

// 默认导出vuex仓库的实例对象
export default new Vuex.Store({
  state: {
    // 任务列表数据
    list: [],
    // 文本输入框中默认输入的内容
    inputValue: 'abc',
    // 按钮的默认状态
    key: 'all'
  },
  mutations: {
    // 初始化任务列表数据
    initList (state, data) {
      state.list = data
    },
    // 将输入框输入的内容更新到数据
    changeInput (state, val) {
      state.inputValue = val
    },
    // 添加任务
    addItem (state) {
      const taskObj = {
        id: state.list.length,
        info: state.inputValue.trim(),
        // 默认false
        done: false
      }
      state.list.push(taskObj)
      // 清空inputValue
      state.inputValue = ''
    },
    // 删除任务
    deleteItem (state, id) {
      const index = state.list.findIndex(item => item.id === id)
      state.list.splice(index, 1)
    },
    // 改变复选框的状态
    changeStatus (state, params) {
      const index = state.list.findIndex(item => item.id === params.id)
      state.list[index].done = params.status
    },
    // 清除已完成任务
    clearDone (state) {
      state.list = state.list.filter(item => item.done === false)
    },
    // 修改按钮的key值
    changeKey (state, key) {
      state.key = key
    }
  },
  actions: {
    getList (context) {
      // 发送请求 获取任务列表数据
      axios.get('/list.json').then(({ data }) => {
        // 触发mutations中的函数
        context.commit('initList', data)
      })
    }
  },
  getters: {
    // 统计未完成任务的条数
    unDoneCount (state) {
      return state.list.filter(item => item.done === false).length
    },
    infoLIst (state) {
      if (state.key === 'all') return state.list
      if (state.key === 'unDone') return state.list.filter(item => item.done === false)
      if (state.key === 'done') return state.list.filter(item => item.done === true)
    }
  }
})
